<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Requests;

use App\Models\Menu;
use App\Services\DictionaryService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

/**
 * 菜单模块表单验证
 * Class MenuRequest
 * @package App\Http\Requests
 */
class MenuRequest extends BaseRequest
{

    /**
     * 注入表单请求验证时自动校验
     *
     * @var bool
     */
    public $autoValidate = false;

    /**
     * 当前经过身份验证的用户是否可以执行请求操作
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 规则
     *
     * @return array
     */
    public function rules()
    {
        $menu = $this->menu;
        return [
            'id' => 'required|integer',
            'created_user_id' => 'required|integer',
            'type' => [
                'required',
                'integer',
                Rule::in(DictionaryService::getItemsValuesArray('menuTypeVar')),
            ],
            'parent_id' => [
                'nullable',
                'integer',
                function ($attribute, $value, $fail) {
                    $this->validateParent(__('menu.parent_id'), $value, $fail);
                }
            ],
            'name' => "required|min:2|max:50",
            'enname' => ['nullable', 'min:2', 'max:100', 'regex:/^[\sa-zA-Z]+$/', Rule::unique('menu')->ignore($menu)->where(function ($query) {
                return $query->where('deleted_at', null);
            })],
            'description' => 'nullable|max:200',
            'sort' => 'required|integer',
            'route_name' => ['required', 'min:2', 'max:50', Rule::unique('menu')->ignore($menu)->where(function ($query) {
                return $query->where('deleted_at', null);
            })],
            'route_icon' => 'nullable|max:50',
            'route_path' => ['required', 'max:255', Rule::unique('menu')->ignore($menu)->where(function ($query) {
                return $query->where('deleted_at', null);
            })],
            'route_component' => 'nullable|max:100',
            'route_redirect' => 'nullable|max:100',
            'route_activeMenu' => 'nullable|max:100',
            'route_alwaysShow' => 'nullable|boolean',
            'route_affix' => 'nullable|boolean',
            'route_breadcrumb' => 'nullable|boolean',
            'route_isTree' => 'nullable|boolean',
            'permission_ids' => 'nullable|array',
            'relation_cate' => [
                'nullable',
                function ($attribute, $value, $fail) use ($menu) {
                    $tempMenu = Menu::where('relation_cate', 1)->first();
                    if ($value > 0 && $this->type != 1) {
                        $fail(__('menu.error_relation_cate_with_type'));
                    }
                    if ($value > 0 && $tempMenu && $tempMenu['id'] != $menu->id) $fail(__('menu.error_times_relation_cate'));
                }
            ],
            'status' => 'required|boolean',
            'sort.*.id' => 'required|integer',
            'sort.*.sort' => 'required|integer',
        ];
    }


    /**
     * 定义场景
     * @var \string[][]
     */
    public $scenes = [
        'store' => [
            'created_user_id',
            'type',
            'parent_id',
            'name',
            'enname',
            'description',
            'sort',
            'route_name',
            'route_icon',
            'route_path',
            'route_component',
            'route_redirect',
            'route_activeMenu',
            'route_alwaysShow',
            'route_affix',
            'route_breadcrumb',
            'route_isTree',
            'relation_cate',
            'status',
            'permission_ids'
        ],
        'update' => [
            'parent_id',
            'name',
            'enname',
            'description',
            'sort',
            'route_name',
            'route_icon',
            'route_path',
            'route_component',
            'route_redirect',
            'route_activeMenu',
            'route_alwaysShow',
            'route_affix',
            'route_breadcrumb',
            'route_isTree',
            'relation_cate',
            'status',
            'permission_ids'
        ],
        'destroy' => ['id'],
        'updateStatus' => ['status'],
        'updateSort' => ['sort.*.id', 'sort.*.sort']
    ];

    /**
     * 验证错误的自定义属性
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'id' => __('common.id'),
            'type' => __('menu.type'),
            'parent_id' => __('menu.parent_id'),
            'name' => __('menu.name'),
            'enname' => __('menu.enname'),
            'description' => __('menu.description'),
            'sort' => __('menu.sort'),
            'route_name' => __('menu.route_name'),
            'route_icon' => __('menu.route_icon'),
            'route_path' => __('menu.route_path'),
            'route_component' => __('menu.route_component'),
            'route_redirect' => __('menu.route_redirect'),
            'route_activeMenu' => __('menu.route_activeMenu'),
            'route_alwaysShow' => __('menu.route_alwaysShow'),
            'route_affix' => __('menu.route_affix'),
            'route_breadcrumb' => __('menu.route_breadcrumb'),
            'route_isTree' => __('menu.route_isTree'),
            'status' => __('common.status'),
            'sort.*.id' => __('common.id'),
            'sort.*.sort' => __('common.sort'),
            'relation_cate' => __('menu.relation_cate'),
        ];
    }

    /**
     * 验证前
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->offsetSet('created_user_id', Auth::id());
        $this->offsetSet('parent_id', isset($this->parent_id) && !empty($this->parent_id) ? $this->parent_id : 0);
        $this->offsetSet('route_affix', isset($this->route_affix) && !empty($this->route_affix) ? $this->route_affix : 0);

        if ($this->type == 1) {// 目录
            $route_component = $this->parent_id > 0 ? "/empty" : "/layout";
            $this->offsetSet('route_component', $route_component);
            $this->offsetSet('route_activeMenu', '');
            $this->offsetSet('route_affix', 0);
            $this->offsetSet('relation_cate', isset($this->relation_cate) && !empty($this->relation_cate) ? $this->relation_cate : 0);
        } else if ($this->type == 2) {// 菜单
            $this->offsetSet('relation_cate', 0);
        } else if ($this->type == 3) {// 链接
            $this->offsetSet('route_component', "/empty");
            $this->offsetSet('route_redirect', '');
            $this->offsetSet('route_activeMenu', '');
            $this->offsetSet('route_alwaysShow', 0);
            $this->offsetSet('route_breadcrumb', 0);
            $this->offsetSet('route_isTree', 0);
            $this->offsetSet('relation_cate', 0);
        }
    }

    /**
     * 判断上一级菜单合法性
     * @param $attribute
     * @param $value
     * @param $fail
     */
    public function validateParent($attribute, $value, &$fail)
    {
        if (!empty($value)) {
            $parent = Menu::find($value);
            if (!$parent) {
                $fail($attribute . __('common.http_not_found'));
            }
            // 上级菜单不可为外链或菜单类型
            if ($parent->type != 1) {
                $fail(__('menu.error_type_range'));
            }

            // 上级菜单不可为绑定栏目的目录
            if ($parent->relation_cate > 0) {
                $fail(__('menu.error_parent_with_relation_cate'));
            }

            // 上级菜单不能选择自身
            if (isset($this->id) && $this->id == $value) {
                $fail(__('menu.error_pid_equal_id'));
            }
        } else {
            // 请选择
            if ($this->type == 2) {
                $fail(__('menu.error_parent_id'));
            }
        }
    }


}


